package com.jungle.client;

import com.jungle.client.dialog.SampleDialog;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.control.MenuItem;
import javafx.scene.layout.BorderPane;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;

@Slf4j
public class MainController implements Initializable {

    @FXML
    private BorderPane mainLayout;
    private ResourceBundle bundle;

    public void initialize(URL location, ResourceBundle resources) {
        log.info("init MainController, location:{}", location);
        this.bundle = resources;
    }

    @FXML
    void onActionMenuExit(ActionEvent actionEvent) {
        log.info("onActionMenuExit {}", actionEvent);
        Platform.exit();
    }

    @FXML
    private void load2Center(ActionEvent event) {
        log.info("load2Center {}", event);
        if (event.getSource() instanceof MenuItem menuItem && menuItem.getUserData() instanceof String resource) {
            loadComponent(resource, mainLayout);
        }
    }

    private void loadComponent(String resource, BorderPane pane) {
        try {
            FXMLLoader loader = new FXMLLoader(getClass().getResource(resource));
            loader.setResources(bundle);
            Parent center = loader.load();
            pane.setCenter(center);
        } catch (IOException e) {
            log.error(bundle.getString("app.error.load.component"), e);
        }
    }

    public void onActionSample(ActionEvent event) {
        log.info("onActionFormSample {}", event);
        SampleDialog dialog = new SampleDialog();
    }
}
